package com.cslg.ac.demo.util.string;

import java.security.MessageDigest;
import java.util.Arrays;

public class EncryptionUtil {

	private static final String ALGORITHM = "MD5";
	private static MessageDigest md5;
	
	static
	{
		try
		{
			md5 = MessageDigest.getInstance(ALGORITHM);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	private static String bytesToHexString(byte[] data)
	{
		StringBuffer sb = new StringBuffer();
		int temp;
		for(int i=0; i<data.length; i++)
		{
			temp = data[i];
			if(temp < 0)
				temp += 256;
			if(temp < 16)
				sb.append("0");
			sb.append(Integer.toHexString(temp));
		}
		return sb.toString();
	}
	
	public static synchronized byte[] getEncryptedBytes(String clearString)
	{
		md5.update(clearString.getBytes());
		return md5.digest();
	}
	
	public static String getEncryptedString(String clearString)
	{
		byte[] bytes = getEncryptedBytes(clearString);
		return bytesToHexString(bytes);
	}

	/**
	 * update表示更新，状态变为当前状态为处理过程中
	 * digest方法表示计算哈希值
	 * @param clearString
	 * @param cipherBytes
	 * @return
	 */
	public static synchronized boolean auth(String clearString, byte[] cipherBytes)
	{
		md5.update(clearString.getBytes());
		byte[] bytes = md5.digest();
		return Arrays.equals(bytes,  cipherBytes);
	}
	
}
